package com.neuedu.weishi.web.Intereptor;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.neuedu.weishi.util.RedisUtils;
import com.neuedu.weishi.util.SignUtils;
import com.neuedu.weishi.vo.ResponseData;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.log4j.Log4j2;
import org.springframework.web.servlet.HandlerInterceptor;
import java.io.IOException;
import java.io.PrintWriter;

import static com.alibaba.fastjson.serializer.SerializerFeature.*;

/**
 * 登录检查拦截器
 */
@Log4j2
public class LoginCheckedInterceptor implements HandlerInterceptor {


    private RedisUtils redisUtils;

    public RedisUtils getRedisUtils() {
        return redisUtils;
    }

    public void setRedisUtils(RedisUtils redisUtils) {
        this.redisUtils = redisUtils;
    }

    /**
     * 登录检查
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String url = request.getRequestURI();
        log.debug("当前请求路径为:" + url);
        String token = request.getParameter("token");
        if (StrUtil.isEmpty(token)) {
            //返回错误信息:缺少token参数
            responseError(999, "缺少token参数", response);
            return false;
        }
        String tokenKey = "login:token:" + token;
        if (!redisUtils.hasKey(tokenKey)) {
            //返回错误信息:token失效
            responseError(999, "token失效", response);
            return false;
        }
        String memberId = (String) redisUtils.get(tokenKey);
        //验证token是否合法
        String currentToken = SignUtils.getToken(false, memberId, request);
        token = SignUtils.removeRandomStr(token);
        if (!token.equals(currentToken)) {
            //返回错误信息:非法的token
            responseError(999, "非法的token", response);
            return false;
        }
        return true;
    }

    /**
     * 响应错误信息
     *
     * @param code    错误码
     * @param message 错误信息
     * @param response 响应对象
     */
    private void responseError(int code, String message, HttpServletResponse response) {
        ResponseData responseData = ResponseData.fail(code, message);
        response.setContentType("application/json;charset=utf-8");
        PrintWriter out = null;
        try {
            out = response.getWriter();
            response.getWriter().write(JSONObject.toJSONString(responseData, WriteNullBooleanAsFalse,
                    WriteNullListAsEmpty,
                    WriteNullStringAsEmpty,
                    WriteNullNumberAsZero,
                    WriteDateUseDateFormat,
                    WriteMapNullValue,
                    PrettyFormat,
                    DisableCircularReferenceDetect,
                    BrowserCompatible));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
